package com.njcb.ams.factory.comm;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

/**
 * 全局信息,绑定此信息的线程在任意地方都能引用
 *
 * @author LIUYANLONG
 *
 */
public class WebGlobalInfo extends DataBus {
	private static final long serialVersionUID = 1L;
	public static String AMS_SESSIONID = "AMS_SESSIONID";
	public String sessionid;

	public static void setGlobalInfo2HttpSession(HttpSession httpSession, WebGlobalInfo globalInfo) {
		globalInfo.setSessionid(httpSession.getId());
		httpSession.setAttribute(DataBus.KEY_GLOBAL_INFO, globalInfo);
	}

	public static DataBus getFromRequest(HttpSession httpSession) {
		WebGlobalInfo globalInfo = (WebGlobalInfo) httpSession.getAttribute(WebGlobalInfo.KEY_GLOBAL_INFO);
		if (null != globalInfo) {
			globalInfo.setSessionid(httpSession.getId());
			setCurrentInstance(globalInfo.clone());
		}
		return globalInfo;
	}
	
	public void setSessionid(String sessionid) {
		this.sessionid = sessionid;
	}
	
	public String getSessionid() {
		return sessionid;
	}
	
	
	@Override
	public WebGlobalInfo clone() {
		WebGlobalInfo webGlobalInfoCopy = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(this);
			ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bais);
			webGlobalInfoCopy = (WebGlobalInfo) ois.readObject();
			Map<String, Object> attributes = getAttributes();
			if(null != attributes){
				for (Entry<String, Object> entry : attributes.entrySet()) {
					webGlobalInfoCopy.addAttribute(entry.getKey(), entry.getValue());
				}
			}
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
			return this;
		}
		return webGlobalInfoCopy;
	}

}